package org.springblade.core.oss.config;

import com.aliyun.oss.ClientConfiguration;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.common.auth.CredentialsProvider;
import com.aliyun.oss.common.auth.DefaultCredentialProvider;
import org.springblade.core.oss.AliossTemplate;
import org.springblade.core.oss.props.OssProperties;
import org.springblade.core.oss.rule.BladeOssRule;
import org.springblade.core.oss.rule.OssRule;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration(
        proxyBeanMethods = false
)
@AutoConfigureAfter({QiniuConfiguration.class})
@EnableConfigurationProperties({OssProperties.class})
@ConditionalOnProperty(
        value = {"oss.name"},
        havingValue = "alioss"
)
public class AliossConfiguration {
    private OssProperties ossProperties;

    @Bean
    @ConditionalOnMissingBean({OssRule.class})
    public OssRule ossRule() {
        return new BladeOssRule();
    }

    @Bean
    @ConditionalOnMissingBean({OSSClient.class})
    public OSSClient ossClient() {
        ClientConfiguration conf = new ClientConfiguration();
        conf.setMaxConnections(1024);
        conf.setSocketTimeout(50000);
        conf.setConnectionTimeout(50000);
        conf.setConnectionRequestTimeout(1000);
        conf.setIdleConnectionTime(60000L);
        conf.setMaxErrorRetry(5);
        CredentialsProvider credentialsProvider = new DefaultCredentialProvider(this.ossProperties.getAccessKey(), this.ossProperties.getSecretKey());
        return new OSSClient(this.ossProperties.getEndpoint(), credentialsProvider, conf);
    }

    @Bean
    @ConditionalOnMissingBean({AliossTemplate.class})
    @ConditionalOnBean({OSSClient.class, OssRule.class})
    public AliossTemplate aliossTemplate(OSSClient ossClient, OssRule ossRule) {
        return new AliossTemplate(ossClient, this.ossProperties, ossRule);
    }

    public AliossConfiguration(final OssProperties ossProperties) {
        this.ossProperties = ossProperties;
    }
}
